import 'package:bot_toast/bot_toast.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:wallpaper/api/bocchi.dart';
import 'package:wallpaper/components/images/image_list.dart';
import 'package:wallpaper/components/input/my_search_input.dart';
import 'package:wallpaper/model/image_base.dart';

class BocchiPage extends StatefulWidget {
  final bool isPC;
  const BocchiPage({super.key, this.isPC = false});

  @override
  State<BocchiPage> createState() => _BocchiPageState();
}

class _BocchiPageState extends State<BocchiPage>
    with SingleTickerProviderStateMixin {
  final List<ImageBase> imgs = [];
  bool isLoading = false;
  int page = 1;
  final int pageSize = 20;
  int totalPages = 0;
  String order = 'DESC'; // DESC:最新 ASC:最早
  final TextEditingController controller = TextEditingController();
  late AnimationController _animationController;

  // 使用ValueNotifier避免不必要的重建
  final ValueNotifier<bool> _isSearchFocused = ValueNotifier(false);

  @override
  void initState() {
    super.initState();
    getBocchiImgs();

    // 初始化动画控制器
    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 300),
      value: 0.0, // 初始值为0.0（对应DESC状态）
    );

    // 监听输入变化，避免频繁重建
    controller.addListener(() {
      // 可以在这里处理实时搜索逻辑，添加防抖
    });
  }

  Future<void> getBocchiImgs() async {
    if (!mounted || isLoading) return;
    setState(() {
      isLoading = true;
    });
    try {
      Response res = await getBocchiWallpapers(
        page: page,
        limit: pageSize,
        q: controller.text,
        type: widget.isPC ? 2 : 1,
        order: order,
      );
      totalPages = res.data['data']['pagination']['totalPages'];
      List bocchi = res.data['data']['items'];
      for (var i = 0; i < bocchi.length; i++) {
        imgs.add(ImageBase(
          largePath: bocchi[i]['url'],
          smallPath: bocchi[i]['cover'],
          tags: bocchi[i]['tags'],
          width: bocchi[i]['width'],
          height: bocchi[i]['height'],
        ));
      }
    } catch (e) {
      debugPrint(e.toString());
    } finally {
      if (mounted) {
        setState(() {
          isLoading = false;
        });
      }
    }
  }

  void switchOrder() {
    setState(() {
      if (order == 'DESC') {
        order = 'ASC';
        _animationController.forward();
        BotToast.showText(text: '最早');
      } else {
        order = 'DESC';
        _animationController.reverse();
        BotToast.showText(text: '最新');
      }
      imgs.clear();
      page = 1;
      totalPages = 0;
    });
    getBocchiImgs();
  }

  // 处理搜索提交
  void _handleSearchSubmitted(String value) {
    page = 1;
    imgs.clear();
    getBocchiImgs();
  }

  @override
  void dispose() {
    controller.dispose();
    _animationController.dispose();
    _isSearchFocused.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context).colorScheme;

    // 使用RepaintBoundary隔离重绘区域
    return RepaintBoundary(
      child: Scaffold(
        resizeToAvoidBottomInset: false,
        floatingActionButton: FloatingActionButton(
          onPressed: switchOrder,
          elevation: 6,
          child: AnimatedIcon(
            icon: AnimatedIcons.home_menu,
            progress: _animationController,
            color: theme.onSurface,
          ),
        ),
        floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
        appBar: AppBar(
          title: const Text(''),
          toolbarHeight: 0,
          elevation: 0,
          leading: null,
          backgroundColor: theme.primaryContainer,
          surfaceTintColor: theme.primaryContainer,
        ),
        body: Column(
          children: [
            // 使用const构造函数并隔离搜索框
            const RepaintBoundary(
              child: _SearchInputSection(),
            ),
            Expanded(
              child: ImageList(
                imageList: imgs,
                isLoading: isLoading,
                isPC: widget.isPC,
                isWaterfallFlow: true,
                onImageBottomLoading: () {
                  if (page >= totalPages) return;
                  page++;
                  getBocchiImgs();
                },
                onImageListRefresh: () {
                  imgs.clear();
                  page = 1;
                  totalPages = 0;
                  getBocchiImgs();
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}

// 将搜索框提取为独立Widget，减少重建范围
class _SearchInputSection extends StatelessWidget {
  const _SearchInputSection();

  @override
  Widget build(BuildContext context) {
    final state = context.findAncestorStateOfType<_BocchiPageState>()!;

    return MySearchInput(
      controller: state.controller,
      onSubmitted: (v) => state._handleSearchSubmitted(v),
    );
  }
}
